<template>
  <div class="face">
    <van-nav-bar
      :title="faceTitle[id]"
      left-arrow
      :safe-area-inset-top="true"
      @click-left="onClickLeft"
    />
    <div class="title">
      <span>{{
        loading ? '人脸识别中...' : faceDetectionText
      }}</span>
    </div>
    <div class="camera">
      <div class="scan">
        <div class="frame">
          <img class="img1" src="../../assets/image/wai.png" alt="">
        </div>
        <div class="frame">
          <img class="img2" src="../../assets/image/zhong.png" alt="">
        </div>
        <div class="frame">
          <img class="img3" src="../../assets/image/nei.png" alt="">
        </div>
      </div>
      <img class="img" :src="faceImg" alt="" v-show="faceImg && faceImgIsShow && id === '0'" />
      <img class="kk" src="../../assets/image/kk.png" v-show="isCreateFace || !isHaveFaceInfo" alt="">
      <video v-show="isShowVideo" id="video" autoplay></video>
      <canvas id="canvas" width="280" height="280"></canvas>
    </div>
    <canvas id="imgcanvas" style="display: none;" width="280" height="280"></canvas>
    <!-- 人脸质量显示区域 -->
    <div class="face-quality" v-if="(id === '0' || id === '1') && isHaveFaceInfo" v-show="!isTest && !isCreateFace">
      <div class="name">人脸照片质量</div>
      <div class="content">
        <div class="item">
          <span class="tag" :style="{backgroundColor: faceImgLeave >= 0 ? levelColor[0] : ''}"></span>
          <span class="text" v-if="faceImgLeave === 0" :style="{color: levelColor[0]}">差</span>
        </div>
        <div class="item">
          <span class="tag" :style="{backgroundColor: faceImgLeave >= 1 ? levelColor[1] : ''}"></span>
          <span class="text" v-if="faceImgLeave === 1" :style="{color: levelColor[1]}">良</span>
        </div>
        <div class="item">
          <span class="tag" :style="{backgroundColor: faceImgLeave >= 2 ? levelColor[2] : ''}"></span>
          <span class="text" v-if="faceImgLeave === 2" :style="{color: levelColor[2]}">优</span>
        </div>   
      </div>
      <div class="tip">如果人脸照片质量差，建议重新录入！</div>
    </div>
    <!-- 按钮区域 -->
    <div class="btn">
      <div
        class="btn_snap"
        v-if="(id === '0' || id === '1')"
        v-show="!isTest && (!isHaveFaceInfo || (isHaveFaceInfo && isCreateFace))"
        :style="{ background: isAgree && !loading ? '#456bfb' : '#CCC' }"
        @click="goCreateFace"
      >
        确定录入
      </div>
      <div class="btn_snap"
        style="background-color: #456bfb;"
        v-if="(id === '0' || id === '1') && isHaveFaceInfo"
        v-show="!isTest && !isCreateFace"
        @click="againCreateFaceHanlde"
      >
        重新录入
      </div>
      <!-- 测试人脸按钮 -->
      <div
        v-if="isHaveFaceInfo && (id === '0' || id === '1') && isTest"
        class="btn_snap"
        @click="againTestFace"
        :style="{ background: isCompleteTest ? '#456bfb' : '#CCC' }"
      >
        重新测试
      </div>
      <div class="btn_snap"
        v-if="isHaveFaceInfo && (id === '0' || id === '1') && !isTest && !isCreateFace"
        style="background-color: #456bfb;"
        @click="goStartTest"
      >
        测试人脸
      </div>
      <div class="btn_snap"
      @click="cancelBtn"
        v-if="isHaveFaceInfo && (id === '0' || id === '1') && (isTest || isCreateFace)"
        style="background-color: #456bfb;"
      >返回</div>
      <!-- <div class="btn_snap" v-if="isTest"
        style="background-color: #456bfb;"
      >取消</div> -->
      <!-- <div
        class="btn_snap"
        @click="goSign"
        :style="{ background: !loading ? '#456bfb' : '#CCC' }"
        v-if="id === '2' || id === '3'"
      >
        {{ id === '2' ? '签到' : '签退' }}
      </div> -->
    </div>
    <!-- 人脸测试信息区域 -->
    <div class="face-test-info" v-if="isHaveFaceInfo && id === '0'" v-show="isTest">
      <div class="info" v-show="testName">检测到的人脸是：<span>{{ testName }}</span></div>
      <!-- <div>可信度：{{ confidence }}</div> -->
    </div>
    
    <!-- 人脸录入协议区域 -->
    <div class="protocol" v-if="id === '0' && (!isHaveFaceInfo || isCreateFace)">
      <div class="content">
        <span
          class="checked"
          @click="toAgree"
          :style="{ color: isAgree ? '#5cacee' : '#f6f6fb' }"
          >✔</span
        >
        您已知悉并同意授权本系统按照<router-link style="color: #5cacee;" to="/agreement">《人脸识别系统协议书》</router-link>实施个人信息采集并用于公司内部管理
      </div>
    </div>
    
    <!-- 地图展开区域 -->
    <van-popup
      v-model:show="popupShow"
      closeable
      position="bottom"
      :style="{ height: '90%' }"
    >
      <div id="mapDom" ref="mapDom"></div>
    </van-popup>
    <!-- 地图展出按钮 -->
    <div class="mapBtn" v-if="(id === '2' || id === '3') && meetingType === '1'">
      <div
        class="btn"
        :style="{ background: locationLoading ? '#456bfb' : '#CCC' }"
        @click="openMap"
      >
        打开地图
      </div>
    </div>
    <!-- <div id="img"></div> -->
    <van-dialog />
  </div>
</template>

<script>
import { onMounted, onBeforeUnmount, computed, ref, watch } from 'vue'
import {
  createFace,
  searchFace,
  faceSignOnline,
  faceSignOffline,
  getFaceSample,
  updateFace
} from '@/api/my/face.js'
import { useStore } from 'vuex'
import { useRoute, useRouter } from 'vue-router'
import { faceTitle, levelColor } from '@/enum.js'
import { Notify, Dialog } from 'vant'
import useCamera from "@/hooks/face/useCamera.js"
import useMap from "@/hooks/face/useMap.js" 
import { baseUrl } from '@/config/env'
import useTracking from '@/hooks/face/useTracking'

export default {
  name: 'Face',
  components: {
    [Dialog.Component.name]: Dialog.Component,
  },
  setup() {
    const store = useStore()
    const route = useRoute()
    const router = useRouter()

    /**
     * 使用钩子函数
     */
    const { getSignConfig, openMap, currentLng, currentLat, mapTimer, popupShow, mapDom, locationLoading} = useMap()
    const { initCamera, getImage, isShowVideo } = useCamera()
    const { openCamera, trackingGetImage, isDetectionFace, closeListen, trackingTitle } = useTracking()
    
    /**
     * 获取对象存储中数据
     */
    const userNumber = computed(() => store.getters.getUserNumber)
    
    /**
     * 接收路由传过来的信息
     */
    // 不同 id 代表不同页面进入人脸识别页面
    const id = route.query.id
    const meetingType = route.query.meetingType || 0
    const meetingId = route.query.meetingId || ''

    /**
     * 全局变量
     */

    // 是否正在录入人脸变量
    let loading = ref(false)
    // 提示文字
    let faceDetectionText = ref('')
    // 照片
    let faceImg = ref("")
    // 是否展示图片
    let faceImgIsShow = ref(false)
    // 是否有人脸信息变量
    let isHaveFaceInfo = ref()
    // 照片质量等级 0-差 1-良 2-优
    let faceImgLeave = ref(0)
    // 是否在创建人脸
    let isCreateFace = ref(false)
    // 是否在测试人脸
    let isTest = ref(false)

    // 是否在发送请求
    let isSendReq = ref(false)

    let timer

    
    // 获取人脸信息
    // type 0 创建人脸
    async function getFaceInfo(type) {
      const res = await getFaceSample({userNumber: userNumber.value})

      console.log(res)

      if (res.data.code === 400) {
        if (id === '0') faceDetectionText.value = "请将头部放入圈内并正视屏幕后点击录入"
        if (id === "2" || id === "3") faceDetectionText.value = "只有录入人脸后才能使用人脸签到功能！"
      } else {
        if (res.data.data.length !== 0) {
          isHaveFaceInfo.value = true

          // 判断签到签退是是否有人脸信息，有则开启自动人脸检测
          if (id === "2" || id === "3") {
            if (isHaveFaceInfo.value)
            openCamera()
          }

          // 判断人脸等级
          const faceScore = res.data.data.faceScore
          if (faceScore >= 92) {
            faceImgLeave.value = 2
          } else if (faceScore >= 80 && faceScore < 92) {
            faceImgLeave.value = 1
          } else {
            faceImgLeave.value = 0
          }

          // 有人脸信息显示其照片
          if (isHaveFaceInfo.value) {
            faceImg.value = `${baseUrl}/images/${res.data.data.facePhoto}`
            faceImgIsShow.value = true
          }

          if (id === '0') faceDetectionText.value = "你已经录入过人脸"
          else faceDetectionText.value = `将人脸对准识别框后开始${id === "2" ? "签到" : "签退"}`

          if (type === 0) faceDetectionText.value = "成功录入人脸"
        }
      }
      
    }
    
  
    /**
     * 创建人脸区域
     */
     
    // 是否同意协议
    let isAgree = ref(false)

    // 创建人脸处理函数
    async function goCreateFace() {
      if (loading.value) {
        return
      } 
      if (!isAgree.value) {
        Notify({
          type: 'warning',
          duration: 1000,
          message: '你还没有勾选协议哦！',
        })
        return
      }


      const image = getImage(userNumber.value)
    
      loading.value = true

      let res

      console.log(isHaveFaceInfo.value)

      // 判断是否录入人脸，有则更新人脸，没有则录入
      if (isHaveFaceInfo.value) {
        res = await updateFace(image)
        loading.value = false
      } else if (!isHaveFaceInfo.value) {
        res = await createFace(image)
        loading.value = false
      } else {
        Notify({ type: 'danger', duration: 3000, message: "未获取到人脸信息，请检查网络状况" })
      }
      

      if (res.data.code === 400) {
        Notify({ type: 'warning', duration: 1000, message: res.data.message })
        faceDetectionText.value = res.data.message
        return
      }

      await getFaceInfo(0)
      cancelBtn()

      if (res.data.data === "创建成功")
        Notify({ type: 'success', duration: 1000, message: '人脸录入成功！' })
      else if (res.data.data === "更新成功")
        Notify({ type: 'success', duration: 1000, message: '人脸更新成功！' })
    }

    // 同意协议处理
    function toAgree() {
      isAgree.value = !isAgree.value
    }

    // 重新创建人脸
    function againCreateFaceHanlde() {
      faceImgIsShow.value = false
      isCreateFace.value = true
      faceDetectionText.value = "请将人脸放入框内后开始录入人脸！"
    }

    /**
     * 测试人脸区域
     */

    // 人脸可信度
    let confidence = ref(0)
    // 测试人名字
    let testName = ref('')
    // 是否完成测试
    let isCompleteTest = ref(false)
    

    // 测试人脸处理函数
    async function goTestFace() {
      // const image = getImage(userNumber.value)
      const image = trackingGetImage(userNumber.value)

      // 开始发送请求
      isSendReq.value = true
      // 开始加载
      loading.value = true

      faceImgIsShow.value = false


      const res = await searchFace(image)

      loading.value = false

      if (res.data.code === 400) {
        const testMessage = res.data.message
        // if (testMessage === "图片不是人脸")
        //   Notify({ type: 'warning', duration: 1000, message: "未检测到人脸" })
        // else
          Notify({ type: 'warning', duration: 1000, message: testMessage })

        // 修改提示文字
        faceDetectionText.value = testMessage

        // 重置名字和可信度
        confidence.value = 0
        testName.value = ''

        // 关闭发送请求，再次识别人脸后发送请求
        isSendReq.value = false
        return
      } else if (res.data.code === 200) {
        // 修改要展示的人脸照片
        isCompleteTest.value = true
        faceImg.value = `${baseUrl}/images/${res.data.data.facePhoto}`
        faceImgIsShow.value = true
        isSendReq.value = false
        closeListen()

        clearTimer()

        // 修改测试文案
        if (res.data.data.length !== 0) {
          confidence.value = res.data.data.confidence
          testName.value = res.data.data.userName
        } else {
          confidence.value = 0
          testName.value = ''
        }

        // 判断人脸是否匹配成功
        if (confidence.value > 55) {
          Notify({ type: 'success', duration: 1000, message: '人脸匹配成功！' })
          faceDetectionText.value = "人脸匹配成功！"
        } else if (confidence.value <= 55) {
          Notify({ type: 'warning', duration: 1000, message: '人脸不匹配！' })
          faceDetectionText.value = "人脸不匹配！"
        }
        
      }  
    }

    // 跳到开始测试
    function goStartTest() {
      isTest.value = true
      faceImgIsShow.value = false 
      faceDetectionText.value = "请将人脸对准框内后开始测试人脸！"
    }

    // 取消按钮
    function cancelBtn() {
      clearTimer()
      faceImgIsShow.value = true
      isCreateFace.value = false
      isTest.value = false
      isCompleteTest.value = false
      testName.value = ""
    }

    // 重新测试按钮
    function againTestFace() {
      clearTimer()
      if (!isCompleteTest.value) return
      faceDetectionText.value = "请将人脸对准框内后开始测试人脸！"
      faceImg.value = ""
      faceImgIsShow.value = false
      isCompleteTest.value = false
      testName.value = ""
      openCamera()

      timer = setTimeout(() => {
        if (!isCompleteTest.value)
          faceDetectionText.value = "请将人脸先移出框内重试！"
      }, 3000)
    }


    /**
     * 签到签退部分
     */

    // 是否获取到位置信息
    let isGetLocation = ref(false)
    

    // 签到处理
    async function goSign() {
      // const image = getImage(userNumber.value)
      isSendReq.value = true

      const image = trackingGetImage(userNumber.value)

      // 开始请求加载
      loading.value = true
      

      //线上人脸签到
      if (meetingType === '0') {
        loading.value = true
        image.append('meetingId', meetingId)

        const res = await faceSignOnline(image)

        // 关闭请求等待
        loading.value = false

        console.log(res)
        if (res.data.code === 400) {
          Notify({ type: 'warning', duration: 1000, message: res.data.message })
          faceDetectionText.value = res.data.message
          isSendReq.value = false
         
        } else if (res.data.code === 200) {
          Notify({ type: 'success', duration: 1000, message: '签到成功' })

          faceDetectionText.value = "签到成功"

          // 关闭活体检测监听
          closeListen()
          
          setTimeout(() => {
            router.go(-1)
          }, 1000)
        }
        loading.value = false
      } 
      // 线下人脸签到
      else if (meetingType === '1') {
        // 判断是否获取到经纬度
        if (currentLat.value === 0 && currentLng.value === 0) {
          isGetLocation.value = true
          Notify({ type: 'warning', duration: 1000, message: "正在获取到当前位置信息，请耐心等待！" })
          isSendReq.value = false
          // 关闭请求等待
          loading.value = false

          faceDetectionText.value = "正在获取到当前位置信息，请耐心等待！"
          return
        }

        image.append("lat", currentLat.value)
        image.append("lng", currentLng.value)
        image.append("meetingId", meetingId)

        // 线下人脸签到
        const res = await faceSignOffline(image)

        // 关闭请求等待
        loading.value = false

        console.log(res)
        if (res.data.code === 400) {
          // Notify({ type: 'warning', duration: 1000, message: res.data.message })
          faceDetectionText.value = res.data.message

          // 关闭请求等待，重新请求
          isSendReq.value = false

        } else {
          Notify({ type: 'success', duration: 1000, message: '签到成功' })
          faceDetectionText.value = "签到成功"

          // 关闭活体检测监听
          closeListen()
          
          setTimeout(() => {
            router.go(-1)
          }, 1000)
        }
        
      }
    }

    /**
     * 点击返回按钮处理函数
     */
    const onClickLeft = () => history.back()

    function clearTimer() {
      if (timer)
        clearTimeout(timer)
    }


    /**
     * 监听区域
     */

     // 监听是否获取到人脸照片
    watch(() => isDetectionFace.value, () => {
      faceDetectionText.value = trackingTitle.value
      
      // 判断是否检测到人脸
      if (isDetectionFace.value && !isSendReq.value) {
        // 判断是在测试人脸还是在签到签退
        if (isTest.value) {
          goTestFace()
        } else {
          goSign()
        }
      }
    })

    // 监听是否在测试人脸
    watch(() => isTest.value, () => {
      // 判断是否在测试人脸， 是则打开活体检测
      if (isTest.value) {
        openCamera()
      } else {
        getFaceInfo()
        closeListen()
      }
    })

    // watch(() => )

    /**
     * 挂载部分
     */
    onMounted(() => {
      if (id === '2' || id === '3') {
        // 获取签到配置信息
        getSignConfig()
      }
      // 初始化摄像头
      initCamera()
      // 获取人脸信息
      getFaceInfo()

      // // 判断是否是签到签退
      // // if (id === "2" || id === "3") {
      //   console.log(isHaveFaceInfo.value)
      //   if (isHaveFaceInfo.value)
      //   openCamera()
      // // }
    })


    /**
     * 卸载部分
     */
    onBeforeUnmount(() => {
      // 退出页面之前关闭摄像头
      window.mediaStreamTrack && window.mediaStreamTrack.stop()
      closeListen()
      // 移除定时器
      clearTimeout(mapTimer)
      clearTimer()
    })

    return {
      id,
      meetingType,
      faceTitle,
      loading,
      confidence,
      testName,
      isAgree,
      isTest,
      isCreateFace,
      faceDetectionText,
      popupShow,
      mapDom,
      isCompleteTest,
      locationLoading,
      faceImgIsShow,
      faceImg,
      faceImgLeave,
      isShowVideo,
      isHaveFaceInfo,
      levelColor,
      onClickLeft,
      goCreateFace,
      goTestFace,
      toAgree,
      goSign,
      openMap,
      againCreateFaceHanlde,
      goStartTest,
      cancelBtn,
      againTestFace
    }
  },
}
</script>

<style lang="scss" scoped>
.face {
  width: 100%;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: var( --global-bg);

  .title {
    width: 100%;
    height: 5rem;
    // background-color: #5cacee;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 1.6rem;
    font-weight: bold;
    color: red;
  }
  #img {
    widows: 100%;
    min-height: 10rem;
  }

  .mapBtn {
    width: 100%;
    height: 10rem;
    display: flex;
    justify-content: center;
    align-items: center;
    .btn {
      width: 20rem;
      height: 5rem;
      // background-color: #5cacee;
      color: var(--btn-text-color);
      border-radius: 1rem;
      text-align: center;
      line-height: 5rem;
    }
  }

  .camera {
    $circle-r: 28rem;

    width: 100%;
    height: 50vh;
    position: relative;
    // display: flex;
    // flex-direction: column;
    // align-items: center;
    // justify-content: center;

    #video {
      width: 28rem;
      height: 28rem;
      border-radius: 50%;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%) rotateY(180deg);
    }

    #canvas {
      border-radius: 50%;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%) rotateY(180deg);
    }

    .scan {
      width: $circle-r;
      height: $circle-r;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      z-index: 1;
      // background-color: red;
      border-radius: 50%;
      
      .frame {
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        border-radius: 50%;
        display: flex;
        justify-content: center;
        align-items: center;
        
        img {
          border-radius: 50%;
        }
        .img1 {
          width: 30.5rem;
          height: 30.5rem;
          // animation: rotation1 3s linear infinite;
        }
        .img2 {
          width: 29.5rem;
          height: 29.5rem;
          animation: rotation2 10s ease-in-out infinite;
          // animation: move2 4s linear infinite;
        }
        .img3 {
          width: 100%;
          height: 100%;
          animation: rotation3 20s ease-in-out infinite;
        }

      }
    }

    .kk {
      width: 28rem;
      height: 28rem;
      border-radius: 50%;
      z-index: 99;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }

    @keyframes rotation2 {
      0% {
        transform: rotate(0);
      }
      50%{
        transform: rotate(180deg);
      }
      100% {
        transform: rotate(0deg);
      }
    }
    @keyframes rotation3 {
      0% {
        transform: rotate(0);
      }
      50% {
        transform: rotate(200deg);
      }
      100% {
        transform: rotate(0deg);
      }
    }

    .img {
      width: 28rem;
      height: 28rem;
      border-radius: 50%;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%) rotateY(180deg);
      // background-color: #666;
      z-index: 10;
    }
  }

  
  .face-test-info {
    width: 100%;
    height: 3rem;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 1rem;

    .info {
      height: 100%;
      line-height: 3rem;
      color: var(--global-second-text-color);

      span {
        color: #000000;
      }
    }
    
  }

  .protocol {
    width: 100%;
    min-height: 6rem;
    box-sizing: border-box;
    padding: 1rem 4rem;
    margin-top: 1rem;

    .content {
      font-size: 1.5rem;
      line-height: 3rem;

      .checked {
        width: 1.5rem;
        height: 1.5rem;
        display: inline-block;
        color: var(--btn-background);
        border: 2px solid #666;
        border-radius: 0.5rem;
        margin-right: 0.5rem;
        // margin-top: 1rem;
        text-align: center;
        line-height: 1.5rem;
      }
    }
  }

  .face-quality {
    $border-r: 0.5rem;

    width: 100%;
    height: 8rem;
    // background-color: orange;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    margin-bottom: 1rem;

    .name {
      font-size: 1.2rem;
      color: var(--gray-color2);
    }
    .content {
      display: flex;
      margin-top: 1.2rem;
      .item {
        width: 5rem;
        // height: 3rem;
        margin-left: 0.2rem;
        display: flex;
        flex-direction: column;
        align-items: center;

        .tag {
          width: 100%;
          height: 0.8rem;
          background-color: #CCC;
          display: block;
        }

        .text {
          margin-top: 0.5rem;
          font-size: 1.2rem;
          font-weight: 600;
        }

        &:nth-child(1) {
          margin-left: 0;
          .tag {
            border-radius: $border-r 0 0 $border-r;
          }
        }
        &:nth-child(3) {
          .tag {
            border-radius: 0 $border-r $border-r 0;
          }
        }
      }
    }

    .tip {
      margin-top: 1.2rem;
      color: red;
      font-size: 1rem;
    }
  }

  .btn {
    width: 100%;
    height: 5rem;
    display: flex;
    align-items: center;
    justify-content: center;
    .btn_snap {
      margin: 0 auto;
      border: 1px solid #f0f0f0;
      // background: #5cacee;
      color: #fff;
      width: 10rem;
      height: 3.6rem;
      line-height: 3.6rem;
      border-radius: 0.8rem;
      text-align: center;
      cursor: pointer;
      cursor: pointer;
      /*禁止选择*/
      -webkit-touch-callout: none;
      /* iOS Safari */
      -webkit-user-select: none;
      /* Chrome/Safari/Opera */
      -khtml-user-select: none;
      /* Konqueror */
      -moz-user-select: none;
      /* Firefox */
      -ms-user-select: none;
      /* Internet Explorer/Edge */
      user-select: none;
      /* Non-prefixed version, currently not supported by any browser */
    }
  }

  #mapDom {
    width: 100%;
    height: 100%;
  }
}
@media screen and (min-width: 700px) {
  

  .camera {
    height: 30vh;
    #video {
      width: 10rem !important;
      height: 10rem !important;
    }

    .scan {
      width: 10rem !important;
      height: 10rem !important;

      .img1 {
        width: 11rem !important;
        height: 11rem !important;
          // animation: rotation1 3s linear infinite;
      }
      .img2 {
        width: 10.5rem !important; 
        height: 10.5rem !important;
      }
      .img3 {
        width: 11.5 !important;
        height: 11.5 !important;
      }

      
    }
    .img, .kk {
        width: 10rem !important;
        height: 10rem !important;
      }

  }

  .btn_snap {
    width: 3rem !important;
    height: 1rem !important;
    line-height: 1rem !important;
    border-radius: 0.3rem !important;
    font-size: 0.3rem;
  }
  
}
</style>